package router

import (
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"path"
	"time"
)

func Router() *gin.Engine {
	r := gin.Default()
	r.GET("/", func(c *gin.Context) {
		time.Sleep(5 * time.Second)
		c.String(http.StatusOK, "Welcome Gin Server")
	})
	r.MaxMultipartMemory = 8 << 20 // 8 MiB
	r.POST("/upload", func(c *gin.Context) {
		// 单文件
		file, _ := c.FormFile("file")
		log.Println(file.Filename)
		if file.Size > 200*1024 {
			c.JSON(http.StatusOK, gin.H{
				"code":    200,
				"message": "图片大于200kb,上传失败",
				"data":    file.Filename,
			})
		} else {
			ext := path.Ext(file.Filename)
			if ext != ".png" {
				c.JSON(http.StatusOK, gin.H{
					"code":    200,
					"message": "图片格式不正确,上传失败",
					"data":    file.Filename,
				})
			} else {
				c.SaveUploadedFile(file, "./files/"+file.Filename)

				c.JSON(http.StatusOK, gin.H{
					"code":    200,
					"message": "上传成功",
					"data":    file.Filename,
				})
			}
		}
	})
	return r
}
